<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>毫秒计时器</title>
        <!-- 使用教程https://picocss.com/docs/forms.html -->
        <link rel="stylesheet" href="../libs/pico.min.css">
        <script src="../libs/TimeFactory.js"></script>
        <script src="../libs/Unify.js"></script>
        <style>
            /* :root {
            --primary: #3949ab;
            } */
        </style>
    </head>
	<body>
        <main id="main" class="container">
            <label for="time">设置时间
                <input type="time" id="timeInput" name="time" value='00:00'>
            </label>
            <article data-theme="light" style="text-align: center;">
                <h6 id="showTime" style="font-size: 100px;">00:00.000</h6>
                <footer><small>时间设置大于0是倒计时，等于0是计时器，使用空格键操作开始停止</small></footer>
            </article>
            <button id="button1" onclick="onBtnClick()">开始</button>
            <button id="button2" onclick="onBtnRecord()">记录</button>
        </main>
        <dialog id="modal-example">
            <article>
              <header>
                <a href="#close" aria-label="Close" class="close" data-target="modal-example" onClick="toggleModal(event)"></a>
                计时器记录
              </header>
              <p id="alert">
                Nunc nec ligula a tortor sollicitudin dictum in vel enim. 
                Quisque facilisis turpis vel eros dictum aliquam et nec turpis. 
                Sed eleifend a dui nec ullamcorper. 
                Praesent vehicula lacus ac justo accumsan ullamcorper.
              </p>
              <footer>
                <a href="#cancel" role="button" class="secondary" onclick="onClose(0)">清空记录</a>
                <a href="#confirm" role="button" onclick="onClose(1)">关闭窗口</a>
              </footer>
            </article>
        </dialog>  
        <audio id='sound' controls="controls" autobuffer="autobuffer" hidden="true">
            <source src="" />
        </audio>
        <script>
            let timeInput=document.getElementById('timeInput');
            let showTime=document.getElementById('showTime');
            let button1=document.getElementById('button1');
            let sound=document.getElementById('sound');
            let dialog=document.getElementById('modal-example');
            let alert=document.getElementById('alert');
            let status=0;
            let sounds=['timeStart','timeStop','timeRestart','timeOver'];
            let btnNames=['开始','停止','重置'];
            let keyTime='keyTime';
            var averages=[];
            var aveTime=0;
            var recGap=2;
            window.addEventListener('keydown', keyDownCallBack,true);
            window.addEventListener('keyup', keyUpCallBack,true);
            if(Unify.isMobile()){//如果在移动端
                recGap=2;
                let button2=document.getElementById('button2');
                button1.style="height: 300px;";
                button2.style="height: 300px;";
                // let main=document.getElementById('main');
                // main.removeChild(button1);
                // main.removeChild(button2);
                // main.appendChild(button1);
                // main.appendChild(button2);
            }
            function keyDownCallBack(e){
                if(status==1){
                    onBtnClick();
                }else if(status==2){
                    onBtnClick();
                }
            }
            function keyUpCallBack(e){
                if(e.code=="Space"){
                    if(status==0){
                        onBtnClick();
                    }
                }
            }
            function onBtnClick(){
                if(status==0){//开始
                    let time=timeInput.value.split(':');
                    time=parseInt(time[0])*60+parseInt(time[1]);
                    if(time>0){
                        TimeFactory.createDownTime(keyTime,time,(data)=>{
                            showTime.innerHTML=data.show;
                            if(data.value==0){
                                status=3;
                                onBtnClick();
                            }
                        },2);
                    }else{
                        TimeFactory.createUpMillisecond(keyTime,0,(data)=>{
                            showTime.innerHTML=data.show;
                            aveTime=data.value;
                        },3);
                    }
                }else if(status==1){//停止
                    TimeFactory.removeTime(keyTime);
                    averages.push(aveTime);
                }else if(status==2){//重置
                    showTime.innerHTML='00:00.000';
                }
                playSound(status);
                ++status;
                if(status>=btnNames.length)status=0;
                button1.innerHTML=btnNames[status];
            }
            function playSound(val){
                let url=`../rec/sound/time/${sounds[val]}.mp3`;
                sound.src=url;
                sound.play();
            }
            function onBtnRecord(){
                let str='';
                let [total,len,timeMin]=[0,averages.length,Infinity];
                for(let i=0;i<len;i++){
                    let t=averages[i];
                    total+=t
                    timeMin=Math.min(t,timeMin);
                    str+=`[${Unify.numberFormat(i+1)}]`+Unify.getMillisecondTimeFormatByNum(t)+((i+1)%recGap!=0?'--------':'<br>');
                }
                aveTime=Unify.getMillisecondTimeFormatByNum(Math.floor(total/len));
                timeMin=Unify.getMillisecondTimeFormatByNum(Math.floor(timeMin));
                str+=`<br>平均:${aveTime}   最快:${timeMin}`;
                //alert(str);
                alert.innerHTML=len==0?'无记录':str;
                dialog.setAttribute("open",true)
                console.log(dialog.article)
            }
            function onClose(e){
                if(e==0){
                    averages.length=0;
                }
                toggleModal();
            }
            function toggleModal(e){
                if(!dialog.hasAttribute("open")){
                    dialog.setAttribute("open",true)
                }else{
                    dialog.removeAttribute("open")
                }
            }
        </script>
    </body>
</html>